package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Entry struct {
	Title     string
	Author    string
	URL       string
	Permalink string
}

type Feed struct {
	Data struct {
		Children []struct {
			Data Entry
		}
	}
}

func main() {
	r := gin.Default()

	r.GET("/JSONP", func(c *gin.Context) {
		data := map[string]interface{}{
			"foo": "bar",
		}

		// /JSONP?callback=x
		// 将输出：x({\"foo\":\"bar\"})
		c.JSONP(http.StatusOK, data)
	})

	r.GET("/books", getBooks)

	// 监听并在 0.0.0.0:8080 上启动服务
	r.Run(":8080")
}

func getBooks(context *gin.Context) {

	var entrys []Entry
	// Create some test entries
	var entry Entry
	entry.URL = "http://www.baidu.com"
	entry.Author = "刘震云"
	entry.Title = "一句顶一万句"
	entry.Permalink = "http://www.baidu.com"

	entry1 := Entry{
		Title:     "Post 1",
		Author:    "John Doe",
		URL:       "https://example.com/post1",
		Permalink: "https://example.com/post1",
	}

	entry2 := Entry{
		Title:     "Post 2",
		Author:    "Jane Doe",
		URL:       "https://example.com/post2",
		Permalink: "https://example.com/post2",
	}
	entrys = append(entrys, entry)
	entrys = append(entrys, entry1)
	entrys = append(entrys, entry2)

	// Create a feed and add the entries
	var feed Feed
	feed.Data.Children = append(feed.Data.Children, struct{ Data Entry }{entry})
	feed.Data.Children = append(feed.Data.Children, struct{ Data Entry }{entry1})
	feed.Data.Children = append(feed.Data.Children, struct{ Data Entry }{entry2})
	books, _ := json.Marshal(feed)
	fmt.Println(string(books))
	context.String(200, string(books))
}
